<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use Illuminate\Support\Facades\Hash;    //引入hash
use App\Services\Cache\AdminCacheService;   //admin缓存
use App\Services\Tools\JwtService;    //引入JWT服务
use App\Services\Tools\FileService;   //引入文件处理类
use App\Response\Response;
use App\Models\MainDB\GiveGiftDay;

class GiftWeekController extends BaseController {

    /**
     * @api {post} /gift_week/list 周星礼物列表
     * @apiVersion 0.1.0
     * @apiName 周星礼物列表
     * @apiGroup 礼物管理
     * @apiParam {string} name   礼物名字，非必传
     * @apiParam {number} gift_id   礼物id，非必传
     * @apiParam {string} start_time    开始时间，非必传
     * @apiParam {string} end_time     结束时间，非必传
     * @apiParam {number} page     页数，非必传
     * @apiParam {number} perPage     每页数量，非必传
     * @apiSuccessExample 成功响应
    {
        "code": 200,
        "data": {
            "list": [
                        {
                        "id(主键id)": 3,
                        "gift_id_1（礼物一id）": 177,
                        "gift_id_2（礼物二id）": 178,
                        "create_time（创建时间）": "2020-04-13 10:09:47",
                        "is_delete（是否过期）": 0,
                        "date（年份和周数）": "2020-18",
                        "gift_name_1（礼物一名字）": "汉堡",
                        "gift_name_2（礼物二名字）": "魔术爱心",
                        "gift_picture_1（礼物一图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ea3f152788dd.png",
                        "gift_picture_2（礼物二图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ea3f18b47a21.png",
                        "start_date（周数的开始日期）": "2020-04-27",
                        "end_date（周数的结束日期）": "2020-05-03"
                        }
                    ],
                "meta": {
                    "page（页数）": 1,
                    "limit（每页数量）": 10,
                    "next（下一页）": null,
                    "total（数据总数）": 8
             }
        }
    }
     *
     */
    public function giftWeekList(Request $request) {
        $page = $request->input('page',1);
        $name = $request->input('name','');
        $gift_id = $request->input('gift_id','');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $perPage = $request->input('perPage',20);
        $time = CommonService::transTime($start_time,$end_time);
        $start_time= $time['start_at'];
        $end_time= $time['end_at'];
        $where =[];
        $where_gift =[];
        $search_time =  [$start_time,$end_time];
        if (!empty($gift_id)){
            $where_gift[] =[function($query) use ($gift_id){
                $query->where('gift_id_1',$gift_id)->orWhere('gift_id_2',$gift_id);
            }];
        }
        if (!empty($name)){
            $where[] =['name','like',"%{$name}%"];
        }
        $giftList= app('repo_gift_week')->giftWeekList($where_gift,$where,$search_time,$page,$perPage);
        if ($giftList){
            foreach ($giftList as $key=>&$value){
                $value->create_time = date('Y-m-d H:i:s',$value->create_time);
                $value->gift_name_1 = $value->gift_one->name;
                $value->gift_name_2 = $value->gift_two->name;
                $value->gift_picture_1 = $value->gift_one->picture;
                $value->gift_picture_2 = $value->gift_two->picture;
                $arr_week_date = explode('-',$value->date);
                $week_date = app('repo_gift_week')->getWeekDate($arr_week_date[0],$arr_week_date[1]);
                $value->start_date =$week_date[0];
                $value->end_date =$week_date[1];
                unset($value->gift_one);
                unset($value->gift_two);
            }
        }
        return Response::sendList($giftList, [], [], $code = 200);
    }

    /**
     * @api {post} /gift_week/add 新增周星礼物
     * @apiVersion 0.1.0
     * @apiName 新增周星礼物
     * @apiGroup 礼物管理
     * @apiParam {number} gift_id_1   礼物一id，必传
     * @apiParam {number} gift_id_2    礼物二id ，必传
     * @apiParam {string} week_date    选取周的结束日期：例如：2020-05-20，必传
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 93028  添加礼物失败
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 93028,
     *          "message": "errorMsg"
     *      }
     *
     */

    public  function  addWeekGift(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'gift_id_1' => 'required|numeric',
                'gift_id_2' => 'required|numeric',
                'week_date' => 'required|date_format:"Y-m-d"',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['gift_id_1', 'gift_id_2']);
        $param['create_time']= time();
        $param['update_time']= time();
        $week_date = $request->input('week_date');
        $weeks = date('Y',strtotime($week_date)).date('W',strtotime($week_date));
        $param['weeks']= $weeks;
        app('repo_gift_week')->addWeekGift($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /gift_week/save 编辑周星礼物
     * @apiVersion 0.1.0
     * @apiName 编辑周星礼物
     * @apiGroup 礼物管理
     *
     * @apiParam {number} id   主键ID，必传
     * @apiParam {number} gift_id_1   礼物一id，必传
     * @apiParam {number} gift_id_2    礼物二id ，必传
     * @apiParam {string} week_date    选取周的结束日期：例如：2020-05-20，非必传
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 930249 编辑周星礼物失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 93029,
     *          "message": "errorMsg"
     *      }
     *
     */
    public  function  saveWeekGift(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'gift_id_1' => 'required|numeric',
                'gift_id_2' => 'required|numeric',
                'week_date' => 'filled|date_format:"Y-m-d"',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['id','gift_id_1', 'gift_id_2']);
        $param['update_time']= time();
        $week_date = $request->input('week_date','');
        if (!empty($week_date)){
            $weeks = date('Y',strtotime($week_date)).date('W',strtotime($week_date));
            $param['weeks']= $weeks;
        }
        app('repo_gift_week')->saveWeekGift($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /gift_week/del 删除周星礼物
     * @apiVersion 0.1.0
     * @apiName 删除周星礼物
     * @apiGroup 礼物管理
     *
     * @apiParam {string} ids   主键（多个用逗号隔开），必传
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 93030  添加礼物失败
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 93030,
     *          "message": "errorMsg"
     *      }
     */
    public  function  delWeekGift(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'ids' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids= $request->input('ids');
        $arr_ids = explode(',',$ids);
        app('repo_gift_week')->delWeekGift($arr_ids);
        return Response::sendData(true);
    }

    /**
     * @api {post} /gift_week/detail 周星礼物详情
     * @apiVersion 0.1.0
     * @apiName 周星礼物详情
     * @apiGroup 礼物管理
     *
     * @apiParam {string} id   周星礼物主键，必传
     * @apiSuccessExample 成功响应
    {
        "code": 200,
        "data": {
                "id(主键id)": 3,
                "gift_id_1（礼物一id）": 177,
                "gift_id_2（礼物二id）": 178,
                "create_time（创建时间）": "2020-04-13 10:09:47",
                "is_delete（是否过期）": 0,
                "date（年份和周数）": "2020-18",
                "gift_name_1（礼物一名字）": "汉堡",
                "gift_name_2（礼物二名字）": "魔术爱心",
                "gift_picture_1（礼物一图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ea3f152788dd.png",
                "gift_picture_2（礼物二图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ea3f18b47a21.png",
                "start_date（周数的开始日期）": "2020-04-27",
                "end_date（周数的结束日期）": "2020-05-03"
        }
    }
     *
     */

    public function  giftWeekDetail(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'id' => 'required|numeric',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $id = $request->input('id');
        $detail = app('repo_gift_week')->giftWeekDetail($id);
        $detail->gift_name_1 = $detail->gift_one->name;
        $detail->gift_name_2 = $detail->gift_two->name;
        $detail->gift_picture_1 = $detail->gift_one->picture;
        $detail->gift_picture_2 = $detail->gift_two->picture;
        $arr_week_date = explode('-',$detail->date);
        $week_date = app('repo_gift_week')->getWeekDate($arr_week_date[0],$arr_week_date[1]);
        $detail->start_date =$week_date[0];
        $detail->end_date =$week_date[1];
        unset($detail->gift_one);
        unset($detail->gift_two);
        return Response::sendData($detail);
    }

    /**
     * @api {post} /gift_week/gift_list 获取奖品列表用于新增 编辑 搜索
     * @apiVersion 0.1.0
     * @apiName 获取奖品列表用于新增 编辑 搜索
     * @apiGroup 礼物管理
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": [
                {
                    "id(主键)": 81,
                    "name（奖品名字）": "梦之承载"
                }
             ]
        }
     *
     */
    public  function  weekGiftList(){
        $detail = app('repo_gift_week')->giftList();
        return Response::sendData($detail);
    }

}
